﻿using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Pdf2epub.BusinessLogic.Extractors.ExtractStrategy;
using Pdf2epub.Interfaces;
using Pdf2epub.Model;

namespace Pdf2epub.BusinessLogic.Extractors
{
    public class PdfFontAnalyzer : IFontAnalyzer
    {
        private readonly IProjectContext m_ProjectContext;

        public PdfFontAnalyzer(IProjectContext projectContext)
        {
            m_ProjectContext = projectContext;
        }

        public FontAnalysisResult Analzye()
        {
            return RunPdfFontAnalysis();
        }

        private FontAnalysisResult RunPdfFontAnalysis()
        {
            m_ProjectContext.FeedbackService.SetDetailText("Getting extraction strategy...");
            HtmlTextExtractionStrategy strategy = new HtmlTextExtractionStrategy(m_ProjectContext) 
            {
                CurrentOperatingMode = OperatingMode.Analyze,
                ImagePath = m_ProjectContext.ProjectConfiguration.ImageOutputPath 
            };

            m_ProjectContext.FeedbackService.SetDetailText(string.Format("Opening document '{0}'", m_ProjectContext.ProjectConfiguration.PdfPath));

            PdfReader pdfReader = new PdfReader(m_ProjectContext.ProjectConfiguration.PdfPath);
            for (int page = 1; page < pdfReader.NumberOfPages; page++)
            {
                m_ProjectContext.FeedbackService.SetDetailText(string.Format("Analysing page {0}/{1}", page, pdfReader.NumberOfPages));
                PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
            }

            return new FontAnalysisResult(strategy.FontUsages,
                                          strategy.AverageLineDistance,
                                          strategy.MinimumLineDistance,
                                          strategy.MaximumLineDistance,
                                          strategy.MostlyUsedLineDistance);
        }
    }
}